package com.quanyan.place.web;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.encrypt.CustomCodec;
import com.quanyan.common.enums.SysParameterConfigEnum;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.place.biz.ConfigService;
import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.entity.Dict;
import com.quanyan.place.entity.TbCommonParameter;
import com.quanyan.place.entity.apireq.ReqCity;
import com.quanyan.place.entity.apireq.ReqKeyWords;
import com.quanyan.place.entity.vo.ReqBaseSearch;
import com.quanyan.place.service.BaseService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 基础模块Controller
 * Created by yangyun on 2016/5/20.
 */
@RestController
@RequestMapping("/admin/api/place/base")
public class BaseController {

    @Autowired
    BaseService baseService;
    @Autowired
    IBaseService iBaseService;

    @Autowired
    private ConfigService configService;

    private Logger logger = LoggerFactory.getLogger(BaseController.class);


    /**
     * 商家端添加城市
     * @param reqCity
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/saveCity", method = RequestMethod.POST)
    public APIResponse<?> saveCity(@RequestBody @Valid ReqCity reqCity, BindingResult bindingResult){
        return  APIResponse.returnSuccess(baseService.saveCity(reqCity));
    }

    /**
     * 商家端更新城市
     * @param reqCity
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/updateCity", method = RequestMethod.POST)
    public APIResponse<?> updateCity(@RequestBody @Valid ReqCity reqCity, BindingResult bindingResult){
        return  APIResponse.returnSuccess(baseService.updateCity(reqCity));
    }

    /**
     * 商家端获取城市列表
     *
     */
    @RequestMapping(value = "/getCityListAdmin", method = RequestMethod.POST)
    public APIResponse<?> getCityListAdmin(@RequestBody @Valid Map<String,Object> map, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return  APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        Integer pageSize = MapUtils.getInteger(map, "pageSize");
        Integer pageNum = MapUtils.getInteger(map, "pageNum");
        String keyWords = null;
        if (StringUtils.isEmpty(MapUtils.getInteger(map, "pageSize"))) {
            pageNum = Constants.DEFAULT_PAGE_NUM;
        }
        if (StringUtils.isEmpty(MapUtils.getInteger(map, "pageNum"))) {
            pageSize = Constants.DEFAULT_PAGE_SIZE;
        }
        if (!StringUtils.isEmpty(MapUtils.getString(map, "keyWords"))) {
            keyWords = MapUtils.getString(map, "keyWords");
        }

        return  APIResponse.returnSuccess(baseService.getCityList(null,pageNum, pageSize,keyWords));
    }

    /**
     * 商家端获取省份列表
     * @return
     */
    @RequestMapping(value = "/getProvinceListAdmin", method = RequestMethod.POST)
    public APIResponse<?> getProvinceListAdmin() {
        return APIResponse.returnSuccess(baseService.getProvinceListAdmin());
    }

    @RequestMapping("/cityTest")
    public String cityTest(){
        return this.iBaseService.getCityTest();
    }

    @RequestMapping(value = "/getCityList", method = RequestMethod.POST)
    public APIResponse<?> getCityList(@RequestParam(value = "provinceId", required = false) Integer provinceId,
                                      @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                      @RequestParam(value = "key", required = false) String keyWords,
                                      HttpServletRequest request) {
        if (pageNum == null){
            pageNum = 0;
        }
        if (pageSize == null){
            pageSize = Constants.DEFAULT_PAGE_SIZE;
        }
        return APIResponse.returnSuccess(baseService.getCityList(provinceId, pageNum, pageSize,keyWords));
    }

    @RequestMapping(value = "/getProvinceList", method = RequestMethod.POST)
    public APIResponse<?> getProvinceList(@RequestParam(value = "pageNum", required = false) Integer pageNum,
                                          @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                          @RequestParam(value = "key", required = false) String keyWords,
                                          HttpServletRequest request) {
        if (pageNum == null){
            pageNum = 0;
        }
        if (pageSize == null){
            pageSize = Constants.DEFAULT_PAGE_SIZE;
        }
        return APIResponse.returnSuccess(baseService.getProvinceList(pageNum, pageSize, keyWords));
    }

    /**
     * 系统参数列表
     * @param reqBaseSearch
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/sysParameterList", method = RequestMethod.POST)
    public APIResponse<?> sysParameterList(@RequestBody @Valid ReqBaseSearch reqBaseSearch, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        Object result = null;
        try {
            result=baseService.getSysParameterList(reqBaseSearch);
            return APIResponse.returnSuccess(result);
        } catch (Exception e) {
            return APIResponse.returnFail(e.getMessage());
        }
    }

    /**
     * 获取系统参数类型
     * @return
     */
    @RequestMapping(value = "/getSysParameterTypeList", method = RequestMethod.GET)
    public APIResponse getSysParameterTypeList(){
        return APIResponse.returnSuccess(SysParameterConfigEnum.getSysConfigEnum());
    }

    /**
     * 新增（修改）系统参数
     * @param sysParameter
     * @return
     */
    @RequestMapping(value="/saveOrUpdateSysParameter",method = RequestMethod.POST)
    public APIResponse<?> saveOrUpdateSysParameter(@RequestBody TbCommonParameter sysParameter){
        APIResponse apiResponse=baseService.saveOrUpdateSysParameter(sysParameter);
        return apiResponse;
    }

    /**
     * 删除系统参数
     * @param id
     * @return
     */
    @RequestMapping(value = "/delSysParameter")
    public APIResponse<?> delSysParameter(@RequestParam(value="id",required =false) Integer id){
        return baseService.sysParameterDelete(id);
    }

    @RequestMapping(value = "/getPlaceOrderRule", method = RequestMethod.GET)
    public APIResponse getPlaceOrderRule(){
        return APIResponse.returnSuccess(baseService.getPlaceOrderRule());
    }

    /**
     * 心跳检测
     * @return
     */
    @RequestMapping(value = "/healthCheck")
    public APIResponse healthCheck(){
        return APIResponse.returnSuccess();
    }

    /************ 维护 字典数据**************/

    /**
     * 获取字典数据列表
     */
    @RequestMapping(value = "/getDicts",method = RequestMethod.POST)
    @CustomCodec(excludes = {"createTime","updateTime","priority","isDelete"})
    public APIResponse<PageObj<List<Dict>>> getDicts(@RequestBody ReqKeyWords reqKeyWords){
        return APIResponse.returnSuccess(baseService.getDicts(reqKeyWords));
    }

    /**
     * 编辑字典数据
     */
    @RequestMapping(value = "/editDict",method = RequestMethod.POST)
    public APIResponse editDict(@RequestBody Dict tbDict,BindingResult bindingResult){
         if(bindingResult.hasErrors()){
             return  APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
         }
        if(ObjectUtil.isObjectEmpty(tbDict)){
            return  APIResponse.returnFail("参数不能为空值！");
        }
        baseService.editDict(tbDict);
        return APIResponse.returnSuccess();
    }

    @RequestMapping(value = "/getCityRegions",method = RequestMethod.POST)
    public APIResponse getCityRegions(@RequestParam(value="cityId",required =false) Integer cityId,BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return  APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        if(ObjectUtil.isObjectEmpty(cityId)){
            return  APIResponse.returnFail("城市id不能为空值！");
        }
        return APIResponse.returnSuccess(configService.getRegionByCityId(cityId.intValue()));
    }
    /**
     * 获取开通城市
     * @return
     */
    @RequestMapping(value = "/getActiveCitys")
    public APIResponse<?> getActiveCitys(@RequestBody @Valid Map<String, Object> map, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        return iBaseService.getCitys(null,true,false,null,null);
    }
}
